import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:hj_crm/const/constant.dart';
import 'package:hj_crm/entity/pagination.dart';
import 'package:hj_crm/entity/distributors/distributor_info.dart';
import 'package:hj_crm/form/distributors/assist_list.dart';
import 'package:hj_crm/form/distributors/distributor_conference_list.dart';
import 'package:hj_crm/form/distributors/distributor_form.dart';
import 'package:hj_crm/form/distributors/distributor_order_list.dart';
import 'package:hj_crm/form/distributors/distributor_outbound_list.dart';
import 'package:hj_crm/http/request_repository.dart';
import 'package:hj_crm/utils/perms_check.dart';
import 'package:hj_crm/widget/load_more_widget.dart';
import 'package:syncfusion_flutter_datagrid/datagrid.dart';

typedef DistributorsChanged = void Function(List<DistributorInfo> distribuors);

/// 经销商列表
class DistributorListWidget extends StatefulWidget {
  final RefreshAction refreshAction;
  const DistributorListWidget({
    super.key,
    required this.refreshAction,
  });

  @override
  State<DistributorListWidget> createState() => _DistributorListState();
}

class _DistributorListState extends State<DistributorListWidget> {
  List<DistributorInfo> distribuors = <DistributorInfo>[];
  DistributorsDataSource? dataSource;

  Pagination? pagination;

  RequestRepository repository = Get.find<RequestRepository>();

  /// 是否滑动
  // bool swiped = false;

  /// 执行删除操作
  bool deleteAction = false;

  // 编辑经销商
  final bool _canUpdate = PermsCheck.distributorUpdate();
  // 删除经销商
  final bool _canDelete = PermsCheck.distributorDelete();
  // 进货情况
  final bool _showOrder = PermsCheck.distributorPurchasePage();
  // 协销情况
  final bool _showAssist = PermsCheck.distributorAssistPage();
  // 参会情况
  final bool _showConference = PermsCheck.distributorConferencePage();
  // 出库情况
  final bool _showOutbound = PermsCheck.distributorOrderPage();

  bool canSwiper = true;

  int maxOffset = 240;

  @override
  void initState() {
    super.initState();

    canSwiper = _canDelete || _showOrder || _showAssist || _showConference || _showOutbound;
    maxOffset = _show(_showOrder) * 60 +
        _show(_showAssist) * 60 +
        _show(_showConference) * 60 +
        _show(_showOutbound) * 60;

    widget.refreshAction(refresh);

    refresh();
  }

  @override
  void dispose() {
    dataSource?.dispose();
    super.dispose();
  }

  refresh() {
    repository.distributorList(
      success: (data) {
        setState(() {
          distribuors = data.data;
          pagination = data.pagination;
          dataSource = DistributorsDataSource(
            distributorData: distribuors,
            pagination: pagination,
            dataChanged: (infos) => distribuors = infos,
          );
        });
      },
    );
  }

  int _show(bool show) => show ? 1 : 0;

  @override
  Widget build(BuildContext context) {
    return dataSource == null
        ? Center(
            child: CircularProgressIndicator(valueColor: AlwaysStoppedAnimation(Colors.deepPurple)))
        : SafeArea(
            child: SfDataGrid(
              source: dataSource!,
              columnWidthMode: ColumnWidthMode.fill,
              selectionMode: deleteAction ? SelectionMode.multiple : SelectionMode.none,

              onCellTap: (details) {
                /// 删除模式下不执行操作
                if (deleteAction) return;

                if (_canUpdate == false) {
                  return;
                }

                if (details.rowColumnIndex.rowIndex == 0) {
                  return;
                }
                // if (swiped) {
                //   dataSource?.notifyListeners();
                //   // swiped = false;
                //   return;
                // }

                // _controller.scrollToHorizontalOffset(0.0);
                // _controller.refreshRow(details.rowColumnIndex.rowIndex - 1);

                Get.to(() => DistributorFormWidget(
                    uId: distribuors[details.rowColumnIndex.rowIndex - 1].id))?.then((v) {
                  if (v == true) refresh();
                });
              },
              allowSwiping: canSwiper,
              swipeMaxOffset: maxOffset.toDouble(),
              allowPullToRefresh: true,
              loadMoreViewBuilder: loadMoreBuilder,
              onSwipeStart: (swipeStartDetails) {
                if (canSwiper == false) {
                  return false;
                }
                if (swipeStartDetails.swipeDirection == DataGridRowSwipeDirection.endToStart) {
                  swipeStartDetails.setSwipeMaxOffset(maxOffset.toDouble());
                } else {
                  swipeStartDetails.setSwipeMaxOffset(_canDelete ? 100 : 0);
                }
                return true;
              },

              // onSwipeUpdate: (swipeUpdateDetails) {
              //   if (swipeUpdateDetails.swipeDirection == DataGridRowSwipeDirection.endToStart &&
              //       swipeUpdateDetails.swipeOffset == 180) {
              //     // swiped = true;
              //     return false;
              //   }

              //   if (swipeUpdateDetails.swipeDirection == DataGridRowSwipeDirection.startToEnd &&
              //       swipeUpdateDetails.swipeOffset == 100) {
              //     // swiped = true;
              //     return false;
              //   }
              //   return true;
              // },
              // onCurrentCellActivating: (newRowColumnIndex, oldRowColumnIndex) {
              //   return false;
              // },
              // onCurrentCellActivated: (newRowColumnIndex, oldRowColumnIndex) {
              //   return;
              // },
              startSwipeActionsBuilder: (context, dataGridRow, rowIndex) {
                return _canDelete
                    ? InkWell(
                        child: Container(
                          height: double.infinity,
                          width: 100,
                          alignment: Alignment.center,
                          color: Colors.red,
                          child: Text('删除'),
                        ),
                        onTap: () {
                          repository.deleteDistributor(
                            ids: [distribuors[rowIndex].id!],
                            success: (data) {
                              // distribuors.removeAt(rowIndex);
                              dataSource?.deleteRow(rowIndex);
                            },
                          );
                        },
                      )
                    : null;
              },
              endSwipeActionsBuilder: (context, dataGridRow, rowIndex) {
                return Row(
                  children: [
                    _showOrder
                        ? InkWell(
                            child: Container(
                              height: double.infinity,
                              width: 60,
                              alignment: Alignment.center,
                              color: Colors.purple,
                              child: Text('进货情况'),
                            ),
                            onTap: () {
                              Get.to(() => DistributorOrderList(uId: distribuors[rowIndex].id!));
                            },
                          )
                        : Container(),
                    _showAssist
                        ? InkWell(
                            child: Container(
                              height: double.infinity,
                              width: 60,
                              alignment: Alignment.center,
                              color: Colors.lightBlue,
                              child: Text('协销情况'),
                            ),
                            onTap: () {
                              Get.to(() => AssistListWidget(uId: distribuors[rowIndex].id!));
                            },
                          )
                        : Container(),
                    _showConference
                        ? InkWell(
                            child: Container(
                              height: double.infinity,
                              width: 60,
                              alignment: Alignment.center,
                              color: Colors.lightGreen,
                              child: Text('参会记录'),
                            ),
                            onTap: () {
                              Get.to(
                                  () => DistributorConferenceList(uId: distribuors[rowIndex].id!));
                            },
                          )
                        : Container(),
                    _showOutbound
                        ? InkWell(
                            child: Container(
                              width: 60,
                              height: double.infinity,
                              alignment: Alignment.center,
                              color: Colors.orange[300],
                              // color: Colors.yellowAccent,

                              child: Text('出库记录'),
                            ),
                            onTap: () {
                              Get.to(() => DistributorOutboundList(uId: distribuors[rowIndex].id!));
                            },
                          )
                        : Container(),
                  ],
                );
              },
              columns: <GridColumn>[
                GridColumn(
                    columnName: 'name',
                    label: Container(
                        padding: EdgeInsets.all(16.0),
                        alignment: Alignment.center,
                        child: Text(
                          '企业名称',
                        ))),
                GridColumn(
                  columnName: 'legal',
                  label: Container(
                    padding: EdgeInsets.all(8.0),
                    alignment: Alignment.center,
                    child: Text('法人'),
                  ),
                ),
                GridColumn(
                    columnName: 'address',
                    label: Container(
                        padding: EdgeInsets.all(8.0),
                        alignment: Alignment.center,
                        child: Text(
                          '公司地址',
                          overflow: TextOverflow.ellipsis,
                        ))),
              ],
            ),
          );
  }
}

class DistributorsDataSource extends DataGridSource {
  DistributorsDataSource({
    required List<DistributorInfo> distributorData,
    Pagination? pagination,
    required DistributorsChanged dataChanged,
  }) {
    _infos = distributorData;
    _pagination = pagination;
    _dataChanged = dataChanged;
    _distributorData = distributorData
        .map<DataGridRow>((e) => DataGridRow(cells: [
              DataGridCell<String>(columnName: 'name', value: e.customerName),
              DataGridCell<String>(columnName: 'legal', value: e.legal),
              DataGridCell<String>(columnName: 'address', value: e.companyAddress),
            ]))
        .toList();
  }

  DistributorsChanged? _dataChanged;

  List<DataGridRow> _distributorData = [];

  int _page = 1;

  Pagination? _pagination;

  List<DistributorInfo> _infos = [];

  @override
  List<DataGridRow> get rows => _distributorData;

  RequestRepository repository = Get.find<RequestRepository>();

  bool get canLoadMore {
    if (_pagination == null) {
      return true;
    }
    if (_page * _pagination!.size! > _pagination!.total!) {
      return false;
    }
    return true;
  }

  /// 删去单行数据
  void deleteRow(int index) {
    _infos.removeAt(index);
    _distributorData.removeAt(index);
    _pagination = Pagination(
      size: _pagination!.size,
      total: (_pagination!.total! - 1),
      page: _page,
    );
    notifyListeners();
  }

  @override
  DataGridRowAdapter buildRow(DataGridRow row) {
    return DataGridRowAdapter(
        cells: row.getCells().map<Widget>((e) {
      return Container(
        alignment: Alignment.center,
        padding: EdgeInsets.all(8.0),
        child: Text(e.value.toString()),
      );
    }).toList());
  }

  @override
  Future<void> handleRefresh() {
    _page = 1;
    repository.distributorList(
      success: (data) {
        _infos = data.data;
        _pagination = data.pagination;
        _dataChanged?.call(_infos);
        _distributorData = _infos
            .map<DataGridRow>((e) => DataGridRow(cells: [
                  DataGridCell<String>(columnName: 'name', value: e.customerName),
                  DataGridCell<String>(columnName: 'legal', value: e.legal),
                  DataGridCell<String>(columnName: 'address', value: e.companyAddress),
                ]))
            .toList();
        notifyListeners();
      },
    );

    return super.handleRefresh();
  }

  @override
  Future<void> handleLoadMoreRows() {
    if (!canLoadMore) {
      return super.handleLoadMoreRows();
    }
    _page++;
    repository.distributorList(
      page: _page,
      success: (data) {
        _infos.addAll(data.data);
        _pagination = data.pagination;
        _dataChanged?.call(_infos);
        _distributorData.addAll(data.data
            .map<DataGridRow>((e) => DataGridRow(cells: [
                  DataGridCell<String>(columnName: 'name', value: e.customerName),
                  DataGridCell<String>(columnName: 'legal', value: e.legal),
                  DataGridCell<String>(columnName: 'address', value: e.companyAddress),
                ]))
            .toList());
        notifyListeners();
      },
    );
    return super.handleLoadMoreRows();
  }
}
